package cz.acies.data.dao;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cz.acies.data.persist.TreeNode;
import cz.acies.face.modul.ModulViewer;
import cz.acies.uniql.sql.SelectQuery;
import cz.acies.uniql.sql.element.UniQLCondition;
import cz.acies.uniql.sql.element.UniQLOrderBy;

public class DesktopDAO extends AbstractDAO
{
	
	public List<ModulViewer> getUIModulDataById(String id) {
		List<ModulViewer> data = new ArrayList<ModulViewer>();
		try {
			QueryRunner qr = new QueryRunner(this.ds());
			SelectQuery sql = new SelectQuery(dbmd()).addFrom("gui_modul")
				.add(new UniQLCondition("modulId", "=", "'"+id+"'"));  
			ResultSetHandler<List<ModulViewer>> handler = new BeanListHandler<ModulViewer>(ModulViewer.class);
			data = qr.query(sql.toSQLString(), handler);
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		return data;
	}
	
	public List<TreeNode> getDesktopMenuData() {
		List<TreeNode> data = new ArrayList<TreeNode>();
		try {
			Map<String, TreeNode> reg = new LinkedHashMap<String, TreeNode>();
			
			QueryRunner qr = new QueryRunner(ds());
			SelectQuery sql = new SelectQuery(dbmd())
			.addFrom("gui_modul_menu")
			.add(new UniQLOrderBy("parentId"))
			.add(new UniQLOrderBy("priority"));
			
			List<Map<String, Object>> menuData = qr.query(sql.toSQLString(), new DefaultMapListHandler(new DefaultRowProcessor()));
			for (Map<String, Object> row : menuData) {
				String id = (String) row.get("id");
				String parentId = (String) row.get("parentId");
				String label = (String) row.get("label");
				String image = (String) row.get("image");
				String modulId = (String) row.get("modulId");
				
				TreeNode parent = reg.get(""+parentId); 
				TreeNode node = new TreeNode(id, label);

				if (parent != null) {
					node.setAttribute("selectable", true);
					if (image != null && image.length() > 0) {
						node.setIconCls(""+image);
					}
					node.setAttribute("modulId", modulId);
					parent.addChild(node);
				} else {
					data.add(node);
				}
				reg.put(id, node);
			}
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		return data;
	}
}
